/*
 * FieldUtil.java
 *
 * Created on February 3, 2006, 5:24 PM
 */

package net.sourceforge.jsorter;

import java.util.*;
import java.util.concurrent.*;
import java.lang.reflect.*;

/**
 *
 * @author  administrator
 * @version
 */
public class FieldUtil {
  private static Map fieldMap = new ConcurrentHashMap();
  
  public static void setFieldValue(String fieldName, Object object, Object value) {
    try {
      Field field = getField(object.getClass(), fieldName);
      field.set(object, value);
    } catch (Exception ex) { ex.printStackTrace(); }
  }
  
  public static Object getFieldValue(String fieldName, Object object) {
    try {
      Field field = getField(object.getClass(), fieldName);
      return field.get(object);
    } catch (Exception ex) { ex.printStackTrace(); return null; }
  }
  
  public static Field getField(Class clazz, String fieldName) {
    Field[] fields = getFields(clazz);
    for (int x=0; x < fields.length; x++) {
      if (fields[x].getName().equals(fieldName)) {
        return fields[x];
      }
    }
    return null;
  }
  
  public static Field[] getFields(Class clazz) {
    Field[] fields = (Field[])fieldMap.get(clazz);
    if (fields != null) return fields;
    List list = new ArrayList();
    getFields(clazz, list);
    
    fields = new Field[list.size()];
    for (int x=0; x < fields.length; x++) {
      fields[x] = (Field)list.get(x);
    }
    fieldMap.put(clazz, fields);
    return fields;
  }
  
  public static void getFields(Class clazz, List list) {
    Class superClass = clazz.getSuperclass();
    if (superClass != null) getFields(superClass, list);
    Field[] fields = clazz.getDeclaredFields();
    for (int x=0; x < fields.length; x++) {
      int modifiers = fields[x].getModifiers();
      if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)
      && !Modifier.isTransient(modifiers) && !Modifier.isFinal(modifiers))
        list.add(fields[x]);
    }
  }
}

